package com.sxhuayuan.parking.job;

import com.sxhuayuan.parking.entity.Invoice;
import com.sxhuayuan.parking.plugin.invoice.InvoicePlugin;
import com.sxhuayuan.parking.service.InvoiceService;
import com.sxhuayuan.parking.service.PluginService;
import com.sxhuayuan.parking.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 发票状态查询任务
 * 
 * @author helong
 * @create 2019/9/3 14:50
 */
@Slf4j
@Component
@Lazy(false)
public class InvoiceQueryJob {
	@Autowired
	PluginService pluginService;
	@Autowired
	InvoiceService invoiceService;
	private static final long FIXED_DELAY = 5*60*1000L;

	/** 查询失败的发票记录，等待下一次查询 */
	private static List<String> failedList = new ArrayList<>();

	/**第一次延迟10秒后执行，之后按fixedDelay的规则每5分钟执行一次*/
	@Scheduled(initialDelay = 10000, fixedDelay = FIXED_DELAY)
	public void queryInvoiceState() {
		String uuid = RandomStringUtils.randomAlphanumeric(8);
		Date now = new Date();
		Date startTime = DateUtils.add(now, Calendar.MINUTE, 5);
		List<Invoice> list = invoiceService.findInvoiceWaitBycreateDate(startTime, now);
		log.debug("[{}] {} --> {} 处于开票中的记录: {}", uuid, DateUtils.format(startTime, "HH:mm:ss"), DateUtils.format(now, "HH:mm:ss"), list.size());
		for (Invoice invoice : list) {
			query(uuid,invoice);
		}
		for (String sn : failedList) {
			Invoice bySn = invoiceService.findBySn(sn);
			query(uuid,bySn);
		}

	}

	private void query(String uuid, Invoice invoice) {
		InvoicePlugin plugin;
		try {
			log.debug("[{}]开票记录 {}", uuid, invoice.getSn());

			plugin = pluginService.getInvoicePlugin(invoice.getPluginId());
			boolean b = plugin.queryInvoiceState(invoice);
			if (b) {
				failedList.remove(invoice.getSn());
			}else {
				log.debug("[{}]查询超时，加入超时列表{}", uuid, invoice.getSn());
				failedList.add(invoice.getSn());
			}
		} catch (Exception e) {
			log.error(uuid, e);
		}
	}
}
